const fs = require("fs");
const http = require("http");

const server = http.createServer((request, response) => {
    // console.log("this is request", getPrototypeChain(response));
    // response.end("Hello world");

    const {url, method, headers} = request;
    if(url === "/" && method === "GET") {
        fs.readFile('index.html', (err, data) => {
            if(err) {
                response.writeHead(500, {
                    "Content-Type": 'text/plain;charset=utf-8'
                });
                response.end("500 服务器出错！");
                return;
            }
            response.statusCode = 200;
            response.setHeader("Content-Type", "text/html");
            response.end(data);
        })
    } else if(method === "GET" && headers.accept.indexOf("image/*") !== -1) {
        fs.createReadStream(`.${url}`).pipe(response);
    } else if(url === "/users" && method === "GET") {
        response.writeHead(200, {
            'Content-Type': "application/json"
        });
        response.end(JSON.stringify([{
            name: "tom",
            age: 21
        }]))
    } else {
        response.statusCode = 404;
        response.setHeader( "Content-Type", 'text/plain;charset=utf-8')
        response.end("404 Not Found.")
    }
})

server.listen(3000, () => {
    console.log("server is start at 3000");
});


function getPrototypeChain(obj){
    const protoChain = []
    while(obj = Object.getPrototypeOf(obj)){
        protoChain.push(obj)
    }
    return protoChain
}